<?php


namespace App\Fastapp\Api\Service\Cms;


use App\Fastapp\Api\Service\BaseService;
use App\Fastapp\Model\FastappAd;
use App\Fastapp\Model\FastappAdPosition;

class PositionService extends BaseService
{
    public function detail(?string $code): array
    {
        $aids = FastappAdPosition::query()->select(['ad_id'])->where(['code' => $code])->value('ad_id');
        if (!$aids) return [];
        $t = time();
        $res = FastappAd::query()
            ->select(['cover', 'cover_theme', 'object_type', 'object_id', 'title', 'url', 'image', 'desc', 'content'])
            ->whereRaw("(start_at < $t and end_at >$t or fixed=1)")
            ->where(['status' => 1])
            ->whereIn('id', $aids)
            ->orderByDesc('sort')
            ->get()->toArray();
        $list = [];
        foreach ($res as $item) {
            $list[] = $this->format($item);
        }
        return ['list' => $list];
    }

    public function ad(string $code): array
    {
        $item = FastappAd::query()->select(['cover', 'cover_theme', 'object_type', 'object_id', 'title', 'url', 'image', 'desc', 'content'])
            ->where(['code' => $code, 'status' => 1])->first();
        if (!$item) return [];
        return $this->format($item->toArray());
    }

    public function format(array $item): array
    {
        $item['cover'] = fastapp_lang_text($item['cover']);
        $item['cover_theme'] = fastapp_lang_text($item['cover_theme']);
        $item['title'] = fastapp_lang_text($item['title']);
        $item['image'] = fastapp_lang_text($item['image']);
        $item['desc'] = fastapp_lang_text($item['desc']);
        $item['content'] = fastapp_lang_text($item['content']);
        return $item;
    }

    public function multi(array $codes): array
    {
        $data = [];
        foreach ($codes as $code) $data[$code] = $this->detail($code)['list'];
        return $data;
    }
}